/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.usergui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import stendcontrol.CoefConfigurator;
import stendcontrol.DataTract;
import stendcontrol.SclVal;

/**
 *
 * @author minaev
 */
public class MovingFrame extends javax.swing.JFrame {

    DataTract dt;
    CoefConfigurator coefc = CoefConfigurator.getConf();
    int currentEngine;
    boolean updateField = false;

    /**
     * Creates new form MovingFrame
     */
    public MovingFrame(DataTract dt) {
        this.dt = dt;
        initComponents();
        jtf_valstep.getDocument().addDocumentListener(new DocumentListener() {
            
            public void change(){
                try {
                    long newval = Long.valueOf(jtf_valstep.getText());
                    jtf_srcstep.setText("" + SclVal.descale(newval,
                            coefc.getPositionCoef0(currentEngine),
                            coefc.getPositionCoefProp(currentEngine)));
                } catch (Exception ex) {
                    //System.out.println("no "+System.currentTimeMillis());
                    //ex.printStackTrace();
                }
            }
            
            @Override
            public void insertUpdate(DocumentEvent e) {
                change();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                change();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });
        updateGUI(0);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jcb_engine = new javax.swing.JComboBox();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jtf_srcstep = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jtf_valstep = new javax.swing.JTextField();
        jb_dec = new javax.swing.JButton();
        jb_inc = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jtf_srcpos = new javax.swing.JTextField();
        jtf_valpos = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jl_speed = new javax.swing.JLabel();
        js_speed = new javax.swing.JSlider();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Позиционирование");

        jLabel1.setText("Двигатель:");

        jcb_engine.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Траверса", "Стол", "Нагружение", "Каретка" }));
        jcb_engine.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcb_engineActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Перемещение"));

        jLabel2.setText("Шаг в единицах двигателя:");

        jtf_srcstep.setText("1000");
        jtf_srcstep.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtf_srcstepActionPerformed(evt);
            }
        });

        jLabel3.setText("Шаг в микрометрах:");

        jtf_valstep.setText("0");
        jtf_valstep.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtf_valstepActionPerformed(evt);
            }
        });

        jb_dec.setText("Уменьшить");
        jb_dec.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_decActionPerformed(evt);
            }
        });

        jb_inc.setText("Увеличить");
        jb_inc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_incActionPerformed(evt);
            }
        });

        jLabel4.setText("Позиция в единицах двигателя:");

        jLabel5.setText("Позиция в единицах величины:");

        jtf_srcpos.setEditable(false);
        jtf_srcpos.setText("0");

        jtf_valpos.setEditable(false);
        jtf_valpos.setText("0");

        jLabel6.setText("Скорость:");

        jl_speed.setText("200");

        js_speed.setMaximum(255);
        js_speed.setValue(200);
        js_speed.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                js_speedStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(js_speed, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtf_srcstep)
                            .addComponent(jtf_valstep)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtf_srcpos)
                            .addComponent(jtf_valpos, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jb_dec)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jb_inc))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jl_speed)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jtf_srcpos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jtf_valpos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jl_speed))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(js_speed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jtf_srcstep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtf_valstep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jb_dec)
                    .addComponent(jb_inc))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jcb_engine, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jcb_engine, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jcb_engineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcb_engineActionPerformed
        int indx = jcb_engine.getSelectedIndex();
        if (indx != -1) {
            currentEngine = indx;
            updateGUI(indx);
        }
    }//GEN-LAST:event_jcb_engineActionPerformed

    private void jb_incActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_incActionPerformed
        jb_inc.setEnabled(false);
        dt.getStendControlApi().setCurrentEngine(currentEngine);
        dt.getStendControlApi().setSpeed(Integer.valueOf(jl_speed.getText()));
        dt.getStendControlApi().goToTargetPosition(currentEngine,
                dt.getStendControlApi().getPosition(currentEngine)
                + Long.valueOf(jtf_srcstep.getText()));
        updateGUI(currentEngine);
        jb_inc.setEnabled(true);
    }//GEN-LAST:event_jb_incActionPerformed

    private void jb_decActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_decActionPerformed
        jb_dec.setEnabled(false);
        dt.getStendControlApi().setCurrentEngine(currentEngine);
        dt.getStendControlApi().setSpeed(Integer.valueOf(jl_speed.getText()));
        dt.getStendControlApi().goToTargetPosition(currentEngine,
                dt.getStendControlApi().getPosition(currentEngine)
                - Long.valueOf(jtf_srcstep.getText()));
        updateGUI(currentEngine);
        jb_dec.setEnabled(true);
    }//GEN-LAST:event_jb_decActionPerformed

    private void jtf_srcstepActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtf_srcstepActionPerformed
        /*try{
         long newval = Long.valueOf(jtf_srcstep.getText());
         jtf_valstep.setText(""+SclVal.scale(newval, 
         coefc.getPositionCoef0(currentEngine), 
         coefc.getPositionCoefProp(currentEngine)));
         }catch(Exception ex){}*/
    }//GEN-LAST:event_jtf_srcstepActionPerformed

    private void jtf_valstepActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtf_valstepActionPerformed
        try {
            System.out.println("test");
            long newval = Long.valueOf(jtf_srcstep.getText());
            jtf_valstep.setText("" + SclVal.scale(newval,
                    coefc.getPositionCoef0(currentEngine),
                    coefc.getPositionCoefProp(currentEngine)));
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_jtf_valstepActionPerformed

    private void js_speedStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_js_speedStateChanged
        jl_speed.setText(""+js_speed.getValue());
    }//GEN-LAST:event_js_speedStateChanged

    private void updateGUI(int engine) {
        currentEngine = engine;
        dt.getStendControlApi().setCurrentEngine(engine);
        jtf_srcpos.setText("" + dt.getStendControlApi().getPosition(engine));
        jtf_valpos.setText("" + dt.getStendControlApi().getScalePosition(engine));
        jtf_valstep.setText(jtf_valstep.getText());
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MovingFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MovingFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MovingFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MovingFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MovingFrame(null).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jb_dec;
    private javax.swing.JButton jb_inc;
    private javax.swing.JComboBox jcb_engine;
    private javax.swing.JLabel jl_speed;
    private javax.swing.JSlider js_speed;
    private javax.swing.JTextField jtf_srcpos;
    private javax.swing.JTextField jtf_srcstep;
    private javax.swing.JTextField jtf_valpos;
    private javax.swing.JTextField jtf_valstep;
    // End of variables declaration//GEN-END:variables
}
